Why does the order of the loops affect performance when iterating over a 2D array? [closed]
        Posted  
        
            by 
                Mark
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Mark
        
        
        
        Published on 2012-03-30T02:17:32Z
        Indexed on 
            2012/09/02
            21:38 UTC
        
        
        Read the original article
        Hit count: 218
        
Possible Duplicate:
Which of these two for loops is more efficient in terms of time and cache performance
Below are two programs that are almost identical except that I switched the i and j variables around. They both run in different amounts of time. Could someone explain why this happens?
Version 1
#include <stdio.h>
#include <stdlib.h>
main () {
  int i,j;
  static int x[4000][4000];
  for (i = 0; i < 4000; i++) {
    for (j = 0; j < 4000; j++) {
      x[j][i] = i + j; }
  }
}
Version 2
#include <stdio.h>
#include <stdlib.h>
main () {
  int i,j;
  static int x[4000][4000];
  for (j = 0; j < 4000; j++) {
     for (i = 0; i < 4000; i++) {
       x[j][i] = i + j; }
   }
}
© Stack Overflow or respective owner